<?php

/*
 * @author Ebrain Cedeno <ebraincedeno@gmail.com>
 */

class ProductController extends Controller{
    
    public function actionGrid(){
        
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        if (isset($_GET['del'])){
            TForm::addMessage("eliminado", "El registro se elimino correctamente");
            $this->validate = new TForm();
            $this->del_product = true;
        }
        else{
            $this->del_product = false;
        }
        
        $this->button_new_product = new TButton("Nuevo Producto");
        $this->button_new_product->Width = 140;
        
        $js_rol = '$(location).attr("href","../product/new");';
        
        $this->button_new_product->onClick = $js_rol;
        $this->button_new_product->OptionsAditional = array('style'=>array('font-weight:bold',
                                                                        'cursor:pointer',
                                                                        'border:1px solid gray',
                                                                        'background-image:url('.VeCms::getPathImage().VeCmsEnum::ICON_ADD.')',
                                                                        'background-position:left',
                                                                        'background-repeat: no-repeat',
                                                                        'background-position-x:5px',
                                                                        'text-align: right'));
        
        $offset = (isset($_GET['offset']))?$_GET['offset']:0;
        $class_product = new product();
        $class_product->Limit = 10;
        $class_product->Offset = $offset;
        
        
        $this->grid_product = new TTable();
        $this->grid_product->Id = "grid-product";
        $this->grid_product->Columns = 7;
        $this->grid_product->Rows = $class_product->Limit;
        $this->grid_product->Width = '100%';
        $this->grid_product->Headers = array('Nro','Codigo','Nombre','Categoria','','','');
        $this->grid_product->WidthCell[0] = 25;
        $this->grid_product->WidthCell[4] = 25;
        $this->grid_product->WidthCell[5] = 25;
        $this->grid_product->WidthCell[6] = 25;
        $this->grid_product->RowsAlign[0] = "center";
        $this->grid_product->Pagination = new TPagination(array('offset'=>$class_product->Offset,'limit'=>$class_product->Limit,'total'=>  product::model()->Count("active=:active",array(":active"=>1))));
        
        $product = $class_product->findAll("active = :active",array(":active"=>1));
        $count = 1;
        foreach ($product as $value){
            
            $view = new TImage();
            $view->Src = VeCms::getPathImage().  VeCmsEnum::ICON_VIEW;
            $view->onClick = '$(location).attr("href","../product/view?id_product='.$value->id_product.'");';
            $view->OptionsAditional['style'][] = 'cursor:pointer';
            $edit = new TImage();
            $edit->Src = VeCms::getPathImage().  VeCmsEnum::ICON_EDIT;
            $edit->onClick = '$(location).attr("href","../product/update?id_product='.$value->id_product.'");';
            $edit->OptionsAditional['style'][] = 'cursor:pointer';
            $delete = new TImage();
            $delete->Src = VeCms::getPathImage().  VeCmsEnum::ICON_DELETE;
            $delete->onClick = 'if (confirm(\'Esta seguro que desea eliminar este producto?\')){
                                    $(location).attr("href","../product/delete?id_product='.$value->id_product.'");
                                }';
            
            $delete->OptionsAditional['style'][] = 'cursor:pointer';
            
            $this->grid_product->Items[] = array($count,$value->code,$value->short_description,$value->category->description,$view->show(),$edit->show(),$delete->show());
            $count++;
        }
                
    }
    
    public function actionGridremote(){
        
        Templete::$theme_name = "PopUp";
        
        $offset = (isset($_GET['offset']))?$_GET['offset']:0;
        $product = new product();
        $product->Offset = $offset;
        $product->Limit = 10;
        
        $this->grid_product_remote = new TTable();
        $this->grid_product_remote->Id = "grid-product-remote";
        $this->grid_product_remote->Columns = 4;
        $this->grid_product_remote->Rows = $product->Limit;
        $this->grid_product_remote->Width = "100%";
        $this->grid_product_remote->Headers = array('Nro','Codigo','Nombre','Precio');
        $this->grid_product_remote->RowsAlign[0]="center";
        $this->grid_product_remote->WidthCell[0]=25;
        $this->grid_product_remote->RowsAlign[1]="center";
        $this->grid_product_remote->RowsAlign[3]="center";
        
        
        
        $product_items = $product->findAll("active = :active",array(":active"=>1));
        $count = 1;
        foreach ($product_items as $key=>$value){
            
            //generando los vinculos para la accion
            
            $inventary = inventory::model()->find("id_product=:id_product",array(":id_product"=>$value->id_product));
            $productJSON = json_encode($inventary);
            
            
            $link_code = new TLink($value->code);
            $link_code->onClick = "add_product('".$productJSON."')";
            $link_code->OptionsAditional['style'][] = 'text-decoration:none';
            $link_code->OptionsAditional['style'][] = 'color:black';
            
            $link_short_description = new TLink($value->short_description);
            $link_short_description->onClick = "add_product('".$productJSON."')";
            $link_short_description->OptionsAditional['style'][] = 'text-decoration:none';
            $link_short_description->OptionsAditional['style'][] = 'color:black';
            
            $link_price = new TLink($inventary->price);
            $link_price->onClick = "add_product('".$productJSON."')";
            $link_price->OptionsAditional['style'][] = 'text-decoration:none';
            $link_price->OptionsAditional['style'][] = 'color:black';
            
            $this->grid_product_remote->Items[]=array($count,$link_code->show(),$link_short_description->show(),  $link_price->show());
            $count++;
        }
        
    }
    
    public function actionAjaxcall(){
        
        if (isset($_POST['id_product'])){
            
            $data = inventory::model()->find("id_product = :id_product",array(":id_product"=>$_POST['id_product']));
            
            $delete = new TImage();
            $delete->Src = VeCms::getPathImage().VeCmsEnum::ICON_DELETE;
            $delete->OptionsAditional['onClick']="delete_product('".$_POST['count']."')";
                
            $delete->OptionsAditional['style'][] = 'cursor:pointer';
            
            // creamos campo de texto oculto para guardar el id del producto y posteriormente podramos recuperarlo :D
            $edit_id_product = new TEdit();
            $edit_id_product->Name = "id_product[]";
            $edit_id_product->Id = $edit_id_product->Name;
            $edit_id_product->Text = $_POST['id_product'];
            $edit_id_product->IsHidden = true;
            
            $edit_price = new TEdit();
            $edit_price->Name = "price[]";
            $edit_price->Id = $edit_price->Name;
            $edit_price->Text = $_POST['price'];
            $edit_price->IsHidden = true;
            
            $edit_amount = new TEdit();
            $edit_amount->Name = "amount_value[]";
            $edit_amount->Id = $edit_price->Name;
            $edit_amount->Text = $_POST['amount'];
            $edit_amount->IsHidden = true;
            
            print "<tr id=\"id_row_".$_POST['count']."\">
                    <td class=\"grid_td\" align=\"center\">".$delete->show()."</td>
                    <td class=\"grid_td\">".$edit_id_product->show().$data->product->short_description."</td>
                    <td class=\"grid_td\">".$edit_amount->show().$_POST['amount']."</td>
                    <td class=\"grid_td\">".$edit_price->show().$_POST['price']."</td>
                    <td class=\"grid_td\">".($_POST['price'] * $_POST['amount'])."</td>
               </tr>";
        }
        
        
    }
    
    public function actionNew(){
        
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        $product = new product();
        $inventary = new inventory();
        
        if (isset($_POST['guardar'])){
            $product->setAttributes($_POST);
            $product->date_register = time();
            $product->id_user = TSession::getSession('user')->id_user;
            $inventary->setAttributes($_POST);
            
            if ($product->validate()){
                
               $inventary->id_product = true;
               $inventary->date_inventary = time();
               
               if ($inventary->validate()){
                   if ($product->save()){
                       $inventary->id_product = $product->id_product;
                       if ($inventary->save()){
                           TForm::addMessage("registrado", "Se ha realizado el registro correctamente");
                           $this->redirec(VeCms::createUrl("./grid"),5);
                       }
                   }
               }
            }
            
            
        }
        
        
        $this->link_back = new TLink("Regresar");
            $js_link = "parent.history.back(); 
                        return false; 
                        ";
         $this->link_back->onClick = $js_link;
         $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
         $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
         
         
         
         $this->form = new TForm();
         $this->form->Method = 'POST';
         $this->form->Action = './new';
         
         $this->code_label = new TLabel("Codigo:");
         $this->code_label->OptionsAditional['style'][] = 'font-weight:bold';
         $this->code_entry = new TEdit();
         $this->code_entry->Name = "code";
         $this->code_entry->Id = $this->code_entry->Name;
         $this->code_entry->Width = 150;
         $this->code_entry->Height = 25;
         $this->code_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
         $this->code_entry->Text = $product->code;
         
         $this->short_description_label = new TLabel("Nombre:");
         $this->short_description_label->OptionsAditional['style'][] = 'font-weight:bold';
         $this->short_description_entry = new TEdit();
         $this->short_description_entry->Name = "short_description";
         $this->short_description_entry->Id = $this->short_description_entry->Name;
         $this->short_description_entry->Width = 250;
         $this->short_description_entry->Height = 25;
         $this->short_description_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
         $this->short_description_entry->Text = $product->short_description;
         
         $this->long_description_label = new TLabel("Descripcion:");
         $this->long_description_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->long_description_text = new TTextView();
         $this->long_description_text->Name = "long_description";
         $this->long_description_text->Id = $this->long_description_text->Name;
         $this->long_description_text->Cols = "10";
         $this->long_description_text->Rows = "10";
         $this->long_description_text->Width = 250;
         $this->long_description_text->Height = 50;
         $this->long_description_text->Text = $product->long_description;
         $this->long_description_text->OptionsAditional['style'] = array('border:1px solid black');

         $this->id_category_label = new TLabel("Categoria:");
         $this->id_category_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->id_category_text = new TComboBox();
         $this->id_category_text->Name = "id_category";
         $this->id_category_text->Id = $this->id_category_text->Name;
         $this->id_category_text->Width = 250;
         $this->id_category_text->Height = 25;
         $this->id_category_text->Selected = $product->id_category;
         
         $estasCategorias = category::model()->findAll("active=:active",array(":active"=>1));
         foreach ($estasCategorias as $value){
             $this->id_category_text->Options[]=array($value->id_category,  ucfirst($value->description));
         }
         
         //iniciamos la carga de la parte de inventario
         
         
         $this->amount_label = new TLabel("Cantidad:");
         $this->amount_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->amount_entry = new TEdit();
         $this->amount_entry->Name = 'amount';
         $this->amount_entry->Id = $this->amount_entry->Name;
         $this->amount_entry->Width = 250;
         $this->amount_entry->Height = 25;
         $this->amount_entry->Text = $inventary->amount;
         $this->amount_entry->OptionsAditional['style'] = array('border:1px solid black');
         
         $this->price_label = new TLabel("Precio:");
         $this->price_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->price_entry = new TEdit();
         $this->price_entry->Name = 'price';
         $this->price_entry->Id = $this->price_entry->Name;
         $this->price_entry->Width = 250;
         $this->price_entry->Height = 25;
         $this->price_entry->Text = $inventary->price;
         $this->price_entry->OptionsAditional['style'] = array('border:1px solid black');
         
         //button
         
         $this->button_reset = new TButton("Cancelar");
         $this->button_reset->Type = "reset";
         $this->button_reset->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));
        
         $this->button_entrar = new TButton("Guardar");
         $this->button_entrar->Name = "guardar";
         $this->button_entrar->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));
         
    }
    
    public function actionUpdate(){
        
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        $class_product = new product();
        $class_inventary = new inventory();
        
        if (isset($_POST['actualizar'])){
                
            $class_product->setAttributes($_POST);
            $class_product->date_register = time();
            $class_product->id_user = TSession::getSession('user')->id_user;
            $class_inventary->setAttributes($_POST);
            
            if ($class_product->validate()){
                
                $class_inventary->id_product = $class_product->id_product;
                $class_inventary->date_inventary = time();
                
                if($class_inventary->validate()){
                    if ($class_product->update()){
                        if ($class_inventary->update()){
                           TForm::addMessage("registrado", "Se ha actualizado el registro correctamente");
                           $this->redirec(VeCms::createUrl("./grid"),5);
                        }
                    }
                } 
                
            }
            
            
        }
        
        $product = $class_product->find("id_product=:id_product",array(':id_product'=>$_GET['id_product']));
        $inventary = $class_inventary->find("id_product=:id_product",array(':id_product'=>$product->id_product));
        
        $this->link_back = new TLink("Regresar");
            $js_link = "parent.history.back(); 
                        return false; 
                        ";
         $this->link_back->onClick = $js_link;
         $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
         $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
         
         
         
         $this->form = new TForm();
         $this->form->Method = 'POST';
         $this->form->Action = './update?id_product='.$_GET['id_product'];
         
         $this->code_label = new TLabel("Codigo:");
         $this->code_label->OptionsAditional['style'][] = 'font-weight:bold';
         $this->code_entry = new TEdit();
         $this->code_entry->Name = "code";
         $this->code_entry->Id = $this->code_entry->Name;
         $this->code_entry->Width = 150;
         $this->code_entry->Height = 25;
         $this->code_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
         $this->code_entry->Text = $product->code;
         
         $this->short_description_label = new TLabel("Nombre:");
         $this->short_description_label->OptionsAditional['style'][] = 'font-weight:bold';
         $this->short_description_entry = new TEdit();
         $this->short_description_entry->Name = "short_description";
         $this->short_description_entry->Id = $this->short_description_entry->Name;
         $this->short_description_entry->Width = 250;
         $this->short_description_entry->Height = 25;
         $this->short_description_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
         $this->short_description_entry->Text = $product->short_description;
         
         $this->long_description_label = new TLabel("Descripcion:");
         $this->long_description_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->long_description_text = new TTextView();
         $this->long_description_text->Name = "long_description";
         $this->long_description_text->Id = $this->long_description_text->Name;
         $this->long_description_text->Cols = "10";
         $this->long_description_text->Rows = "10";
         $this->long_description_text->Width = 250;
         $this->long_description_text->Height = 50;
         $this->long_description_text->Text = $product->long_description;
         $this->long_description_text->OptionsAditional['style'] = array('border:1px solid black');

         $this->id_category_label = new TLabel("Categoria:");
         $this->id_category_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->id_category_text = new TComboBox();
         $this->id_category_text->Name = "id_category";
         $this->id_category_text->Id = $this->id_category_text->Name;
         $this->id_category_text->Width = 250;
         $this->id_category_text->Height = 25;
         $this->id_category_text->Selected = $product->id_category;
         
         $estasCategorias = category::model()->findAll("active=:active",array(":active"=>1));
         foreach ($estasCategorias as $value){
             $this->id_category_text->Options[]=array($value->id_category,  ucfirst($value->description));
         }
         
         //iniciamos la carga de la parte de inventario
         
         
         $this->amount_label = new TLabel("Cantidad:");
         $this->amount_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->amount_entry = new TEdit();
         $this->amount_entry->Name = 'amount';
         $this->amount_entry->Id = $this->amount_entry->Name;
         $this->amount_entry->Width = 250;
         $this->amount_entry->Height = 25;
         $this->amount_entry->Text = $inventary->amount;
         $this->amount_entry->OptionsAditional['style'] = array('border:1px solid black');
         
         $this->price_label = new TLabel("Precio:");
         $this->price_label->OptionsAditional['style'][] = 'font-weight:bold';
         
         $this->price_entry = new TEdit();
         $this->price_entry->Name = 'price';
         $this->price_entry->Id = $this->price_entry->Name;
         $this->price_entry->Width = 250;
         $this->price_entry->Height = 25;
         $this->price_entry->Text = $inventary->price;
         $this->price_entry->OptionsAditional['style'] = array('border:1px solid black');
         
         // campos ocultos
         
         $this->id_product_hidden = new TEdit();
         $this->id_product_hidden->Name = "id_product";
         $this->id_product_hidden->Type = 'text';
         $this->id_product_hidden->Text = $product->id_product;
         $this->id_product_hidden->IsHidden = true;
         
         $this->id_inventary_hidden = new TEdit();
         $this->id_inventary_hidden->Name = "id_inventary";
         $this->id_product_hidden->Type = 'text';
         $this->id_inventary_hidden->Text = $inventary->id_inventary;
         $this->id_inventary_hidden->IsHidden = true;
         
         
         //button
         
         $this->button_reset = new TButton("Cancelar");
         $this->button_reset->Type = "reset";
         $this->button_reset->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));
        
         $this->button_entrar = new TButton("Actualizar");
         $this->button_entrar->Name = "actualizar";
         $this->button_entrar->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));
        
    }
    
    public function actionDelete(){
        
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        if (isset($_GET['id_product'])){
            $product = product::model()->find("id_product=:id_product",array(":id_product"=>$_GET['id_product']));
            $product->active = 0;
            $valid = true;
            if ($product->update()){
                $inventary = inventory::model()->findAll("id_product=:id_product",array(":id_product"=>$product->id_product));
                foreach ($inventary as $value){
                    print $value->id_product."<br/>";
                    $value->active = 0;
                    if (!$value->update()){
                        $valid = false;
                    }
                }
                
                if ($valid == true){
                    $this->redirec(VeCms::createUrl("./grid"),0,array('del'=>true));
                }
                else{
                    throw new Exception("Error al intentar eliminar el registro solicitado");
                }
                
            }
            else{
                throw new Exception("Error al intentar eliminar el registro solicitado");
            }
            
        }
        else{
            throw new Exception("Error al intentar eliminar el registro solicitado");
        }
    }
    
    public function actionView(){
        
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        if (isset($_GET['id_product'])){
            
            $product = product::model()->find("id_product=:id_product",array(":id_product"=>$_GET['id_product']));
            $inventary = inventory::model()->find("id_product=:id_product",array(":id_product"=>$product->id_product));
            
            $this->link_back = new TLink("Regresar");
                $js_link = "parent.history.back(); 
                            return false; 
                            ";
            $this->link_back->onClick = $js_link;
            $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
            $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
            
            $this->code_label = new TLabel("Codigo:");
            $this->code_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->code_value = new TLabel($product->code);
            
            $this->short_description_label = new TLabel("Nombre:");
            $this->short_description_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->short_description_value = new TLabel($product->short_description);
            
            $this->long_description_label = new TLabel("Descripcion:");
            $this->long_description_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->long_description_value = new TLabel($product->long_description);
            
            $this->id_category_description_label = new TLabel("Categoria:");
            $this->id_category_description_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->id_category_description_value = new TLabel($product->category->description);
            
            $this->date_register_label = new TLabel("Registrado El:");
            $this->date_register_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->date_register_value = new TLabel(date("d-m-Y",$product->date_register));
            
            $this->amount_label = new TLabel("Cantidad:");
            $this->amount_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->amount_value = new TLabel($inventary->amount);
            
            $this->price_label = new TLabel("Precio:");
            $this->price_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->price_value = new TLabel($inventary->price);
            
            $this->date_inventary_label = new TLabel("Altualizado El:");
            $this->date_inventary_label->OptionsAditional['style'][] = "font-weight:bold";
            $this->date_inventary_value = new TLabel(date("d-m-Y",$inventary->date_inventary));
            
        }
        else{
            throw new Exception("Error al generar la vista");
        }
        
        
    }
    
}

?>
